<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input v-model="keyword" style="margin-bottom:10px" type="text" prefix-icon="el-icon-search" size="small" placeholder="输入员工姓名全员搜索" @input="handleInput" />
        <!-- 树形组件 -->
        <el-tree
          ref="tree"
          :data="depts"
          :props="{label:'name'}"
          default-expand-all=""
          :expand-on-click-node="false"
          highlight-current
          node-key="id"
          @current-change="handleCurrentChange"
        />
      </div>

      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>

          <el-button size="mini" @click="showDialog=true">excel导入</el-button>

          <el-button size="mini" :loading="loading" @click="handleExport">excel导出</el-button>

        </el-row>

        <!-- 表格组件 -->
        <!-- 分页 -->
        <el-table :data="rows">
          <el-table-column align="center" label="头像">
            <template #default="{row}">
              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" />
              <span v-else class="hhh">{{ row.username.slice(2,3) }} </span>
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="手机号" sortable prop="mobile" />
          <el-table-column label="工号" sortable prop="workNumber" />
          <el-table-column label="聘用形式">
            <template #default="{row}">
              <span>{{ row.formOfEmployment === 1 ? '正式': '🐂🐴' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry" />
          <el-table-column label="操作" width="280px">
            <template #default="{row}">
              <el-button size="mini" type="text" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>

              <el-button size="mini" type="text">角色</el-button>

              <el-popconfirm title="确认删除该行数据吗？" @onConfirm="confirmDel(row.id)">
                <el-button slot="reference" style="margin-left:10px" size="mini" type="text">删除</el-button>

              </el-popconfirm>

            </template>

          </el-table-column>

        </el-table>

        <!-- 分页 -->
        <el-row style="height: 60px" align="middle" type="flex" justify="end">
          <el-pagination
            layout="total,prev, pager, next"
            :total="total"
            :current-page="page"
            @current-change="handlePageChange"
          />
          />
        </el-row>

      </div>
      <!-- 导入excel的对话框 -->
      <!-- <ImportExcel :value="showDialog" @input="showDialog=$event">123</ImportExcel> -->
      <ImportExcel v-model="showDialog" @refresh="getEmployeeList" />
    </div>

  </div>

</template>

<script>
import { getDepartments } from '@/api/department'
import { transList2TreeData } from '@/utils'
import { getEmployeeList, getFileData, delEmployee } from '@/api/employess'
import FileSaver from 'file-saver'
import ImportExcel from './components/import-excel'
export default {
  name: 'Employee',
  components: {
    ImportExcel
  },
  data() {
    return {
      depts: [],
      selectId: null, // 记录当前点击的节点
      total: 0,
      rows: [],
      page: 1,
      keyword: '', // 输入的关键字
      // timer: null// 存定时器id  因为定时器ID不需要在页面展示，所以不在data提供也可以
      loading: false,
      showDialog: false// 控制导入对话框
    }
  },
  created() {
    this.getDepts()
  },
  methods: {
    // 获取树形数据
    async getDepts() {
      const res = await getDepartments()
      this.depts = transList2TreeData(res, 0)
      // 一进入页面 用户不选择部门时 也需要默认获取传智教育的所有员工进行展示
      this.selectId = this.depts[0].id
      // 等tree渲染完成后 才高亮
      this.$nextTick(() => {
        this.$refs.tree.setCurrentKey(this.selectId)
      })
      this.getEmployeeList()// 获取传智教育下所有的员工
    },
    // 监听点击当前节点
    handleCurrentChange(obj) {
      this.selectId = obj.id
      this.page = 1// 重置页面在获取数据 否则拿不到数据
      this.getEmployeeList()// 获取当前点击节点下所有的员工
    },
    // 获取右边列表数据
    async getEmployeeList() {
      const { total, rows } = await getEmployeeList({
        page: this.page,
        pageSize: 5,
        departmentId: this.selectId,
        keyword: this.keyword
      })
      this.total = total
      this.rows = rows
    },
    // 当页面发生变化时重新获取
    handlePageChange(val) {
      this.page = val
      this.getEmployeeList()
    },
    // 监听用户输入的关键字,一旦发现输入内容不变化0.5秒后就会发送请求
    handleInput() {
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.page = 1// 搜索之前页码重置
        this.getEmployeeList()
      }, 500)
    },
    // 导出文件
    async handleExport() {
      try {
        this.loading = true
        const res = await getFileData()
        console.log(res)
        FileSaver.saveAs(res, '员工数据.xlsx')
      } catch {
        this.$message.error('文件下载失败')
        // 不管是成功还是失败都会走这里
      } finally {
        this.loading = false
      }
    },
    // 删除员工方法
    async confirmDel(id) {
      await delEmployee(id)
      if (this.depts.length === 1 && this.page > 1) this.page--
      this.getEmployeeList()
      this.$message.success('删除员工成功')
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin:10px ;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
  }
}
.hhh {
  display: inline-block;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #8df;

  text-align: center;
  line-height: 40px;
  color: #fff;
  font-size: 20px;
}

</style>
